import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import Service from '@/public/http/services';
import { Icon, Modal, Form, Input, Upload, Radio, Select } from 'antd';
import style from './index.css';
const { TextArea } = Input;
const CreateModal: React.FC<any> = ({ formData, visible, title, onOK, onCancel, form, dispatch }) => {

    const [curFileList, setCurFileList] = useState([]);
    const [curmeth, setCurmeth] = useState(0);
    const [parentlist, setParentlist] = useState([]);
    useEffect(() => {
        if (formData && Object.keys(formData).length) {
            setCurFileList([{ uid: formData.id, url: formData.picUrl }] as any)
            setCurmeth(formData.type)
        }
        formData.suffixId = getURLParam(formData.content,'id')
        getplist()
    }, [formData])

    const formItemLayout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 14 },
    }

    const  getURLParam = (url:string,name:string)=> {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      if(!url || url.indexOf('?') == -1){
        return ''
      }
      url = '?' + url.split('?')[1]
      var r = url.substr(1).match(reg);
      if (r != null) return decodeURI(r[2]);
      return null;
    }

  const { getFieldDecorator } = form;

    const [loading, setLoading] = useState(false);

    const uploadSuccess = (file, fileObj) => {
        setLoading(false);
        const { uid, name } = fileObj;
        setCurFileList([{
            uid,
            name,
            url: curFileUrl,
        }] as any);
    }

    const handleChange = (res) => {
        console.log(res)
    }
    const getplist=()=>{
      Service.queryAllParentList().then((res) => {
        var arry:any[] = []
        for(let key in res){
          let json = {
            keyname : key,
            keyvalue : res[key]
          }
          arry.push(json)
        }
        setParentlist(arry as any)
      })
    }
    const [curActionUrl, setCurActionUrl] = useState();
    const [curUploadData, setCurUploadData] = useState({});
    const [curFileUrl, setCurUrl] = useState('');
    const beforeUpload = async (file) => {
        setLoading(true);
        const result = await Service.uploadFileDirect();
        const { host, policy, accessid, signature } = result;
        setCurActionUrl(host);
        const timetamp = new Date().getTime();
        const key = timetamp + '.' + file.name.split('.').pop()
        setCurUrl(host + '/' + key)
        setCurUploadData({
            key,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status: '200',
            signature
        });
        return true;
    }

    const removeSuccess = () => {
        setCurFileList([] as any);
    }
    const changemethod = (e)=>{
      setCurmeth(e.target.value)
    }
    /**
     * @desc 文章插图上传配置
     */
    const upload: any = {
        name: 'file',
        action: curActionUrl,//上传接口，成功后返回该图片服务器地址
        headers: {
            authorization: 'authorization-text',
        },
        onRemove:removeSuccess,
        onSuccess:uploadSuccess,
        onChange: handleChange,
        beforeUpload: beforeUpload,
        data: curUploadData
    }

    return (
        <Modal
            visible={visible}
            title={title}
            okText={'保存'}
            cancelText={'取消'}
            onOk={() => {
                setCurFileList([])
                onOK && onOK(form, {
                    files: curFileList
                })
            }}
            onCancel={() => {
                setCurFileList([])
                onCancel(form)
            }}
            width={'65%'}
        >
            <Form.Item {...formItemLayout} label={'Banner名称'}>
                {
                    getFieldDecorator('name', {
                        initialValue: formData.name,
                        rules: [{ required: true, message: '请输入Banner名称' }],
                    })(<Input placeholder={'请输入Banner名称'} />)
                }
            </Form.Item>
            <Form.Item className={style.mb0} {...formItemLayout} label={'Banner图'}>
                {
                    getFieldDecorator('picUrl', {
                        initialValue: curFileList.length ? (curFileList[0] as any).url : '',
                        rules: [{ required: true, message: '请上传Banner图' }],
                    })(<Upload
                        className={style['upload-btn']}
                        listType='picture-card'
                        {...upload}
                        fileList={curFileList}
                    >
                        <div>
                            <Icon type={loading ? 'loading' : 'plus'} />
                            <div className='ant-upload-text'>上传</div>
                        </div>
                    </Upload>)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'跳转方式'}>
                {
                    getFieldDecorator('type', {
                        initialValue: formData.type,
                        rules: [{ required: true, message: '请选择跳转方式' }],
                    })(<Radio.Group name='type' onChange={changemethod}>
                        <Radio value={1}>内部跳转</Radio>
                        <Radio value={2}>H5跳转</Radio>
                      </Radio.Group>)
                }
            </Form.Item>

          {
            curmeth==2 ? <Form.Item {...formItemLayout} label={'跳转地址'}>
              {
                getFieldDecorator('content', {
                  initialValue: formData.content,
                  rules: [{ required: true, message: '请输入跳转地址' }],
                })(<Input placeholder={'请输入跳转地址'}/>)
              }
            </Form.Item> : null
          }

          {
            curmeth == 1 ? <Form.Item {...formItemLayout} label={'资源前缀'}>
              {
                getFieldDecorator('prefixType', {
                  initialValue: formData.prefixType,
                  rules: [{ required: true, message: '请选择资源前缀' }],
                })(<Select className={style.w220} placeholder={'请选择资源前缀'}>
                  {parentlist.map((item:any,index) =>
                    <Select.Option value={item.keyname} key={index}>{item.keyvalue}</Select.Option>
                  )}

                </Select>)
              }
            </Form.Item> : null
          }
          {
            curmeth == 1 ? <Form.Item {...formItemLayout} label={'资源编号'}>
              {
                getFieldDecorator('suffixId', {
                  initialValue: formData.suffixId,
                  rules: [{ required: true, message: '请输入资源编号' }],
                })(<Input placeholder={'请输入资源编号'}/>)
              }
            </Form.Item> : null
          }

            <Form.Item {...formItemLayout} label={'备注'}>
                {
                    getFieldDecorator('remark', {
                        initialValue: formData.remark,
                    })(<TextArea placeholder={'备注'} />)
                }
            </Form.Item>
        </Modal>
    );
}
const WrappedCreateModal = Form.create<any>({ name: 'modalForm' })(CreateModal);
export default connect((state: any) => {
    return {}
})(WrappedCreateModal);
